package com.menu.Service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.menu.Mapper.IngredientsMapper;
import com.menu.Mapper.MenuMapper;
import com.menu.Mapper.StepMapper;
import com.menu.Mapper.UserMapper;
import com.menu.Pojo.Ingredients;
import com.menu.Pojo.Menu;
import com.menu.Pojo.Step;
import com.menu.Pojo.User;
import com.menu.Service.MenuService;
import com.menu.Service.NoticeService;
import com.menu.Service.StepService;
import com.menu.Utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class MenuServiceImpl implements MenuService {
    @Resource
    MenuMapper menuMapper;
    @Resource
    IngredientsMapper ingredientsMapper;
    @Resource
    StepMapper stepMapper;
    @Resource
    UserMapper userMapper;
    @Autowired
    FileUtils fileUtils;
    @Resource
    StepService stepService;
    @Resource
    NoticeService noticeService;
    @Resource
    RedisUtil redisUtil;

    public final static String UPLOAD_PATH_PREFIX="/static/upload/";

//审核功能,菜谱上传功能,食材功能,推荐关键词搜索功能
    @Override
    public ResponseResult addMenu(MultipartFile menuSrc, String difficulty, String cookTime, String introduce, Integer userId,
                                  String tips,String menuName) {
        User user= userMapper.findByUserId(userId);
        if (user == null) {
            return ResponseResult.error("不存在该用户");
        }
        Date date=new Date();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date1=simpleDateFormat.format(date);
        Menu menu=new Menu();
        menu.setUserId(userId);
        menu.setCookTime(cookTime);
        menu.setReleaseTime(date1);
        menu.setIntroduce(introduce);
        menu.setOfComplete(1);
        menu.setTips(tips);
        menu.setDifficulty(difficulty);
        menu.setMenuName(menuName);
        //添加其余信息
        menuMapper.addMenuBasic(menu);
        //上传封面照
        ResponseResult responseResult=fileUtils.uploadMenu(menuSrc, menu.getMenuId());
        if(responseResult.getCode()==200){
            Object object=responseResult.getObject();
            String fileName=(String)object;
            menuMapper.updateMenuSrc(fileName,menu.getMenuId());
        } else{
            return responseResult;
        }
//        //填写食材信息
//        for(Ingredients ingredients1:ingredientsList){
//            if(ingredients1!=null){
//                ingredientsMapper.addIngredients(ingredients1);
//            }else{
//                responseResult.setMessage("请填写完整的食材信息");
//                return responseResult;
//            }
//        }
//        List<Integer> integers= ingredientsMapper.findAllIngredientsIdByMenuId(menu.getMenuId());
//        menuMapper.updateIngredientsIds(integers.toString(),menu.getMenuId());
//        //填写步骤
//        for (Step step:stepList){
//            if(step!=null){
//                stepMapper.addStep(step);
//            }else{
//                responseResult.setMessage("请填写完整的步骤信息");
//                return responseResult;
//            }
//        }
//        List<Integer> list=stepMapper.findAllStepIdsByMenuId(menu.getMenuId());
//        menuMapper.updateStepIds(list.toString(),menu.getMenuId());
        Menu menu1=menuMapper.findByMenuId(menu.getMenuId());
        return ResponseResult.success("上传成功",menu1);
    }

    @Override
    public ResponseResult findMenuByKeyWord(String keyWord,int pageNow,int pageSize) {
        PageHelper.startPage(pageNow,pageSize);
        List<Menu> menuList=menuMapper.findByMenuNameLike(keyWord);
        PageInfo<Menu> pageInfo=new PageInfo<>(menuList);
        return ResponseResult.success("查询成功",pageInfo);
    }

    @Override
    public ResponseResult findAllMenu(Integer pageNow, Integer pageSize) {
        PageHelper.startPage(pageNow,pageSize);
        List<Menu> menuList=menuMapper.findAllMenu();
        PageInfo<Menu> pageInfo=new PageInfo<>(menuList);
        return ResponseResult.success("查询成功",pageInfo);

    }

    @Override
    public ResponseResult findAllNearTimeMenu(Integer pageNow,Integer pageSize) {
        PageHelper.startPage(pageNow,pageSize);
        List<Menu> menuList=menuMapper.findAllNearTimeMenu();
        PageInfo<Menu> pageInfo=new PageInfo<>(menuList);
        return ResponseResult.success("查询成功",pageInfo);
    }

    @Override
    public ResponseResult findMenuById(Integer menuId) {
        Menu menu=menuMapper.findByMenuId(menuId);
        if (menu == null) {
            return ResponseResult.error("该食谱不存在");
        }
        ArrayList<Ingredients> ingredientsList=new ArrayList<>();
        if(!(menu.getIngredientIds()==null)){
            String[]ingredientIds= CommonUtil.split(menu.getIngredientIds());
            if(!ingredientIds[0].equals("")){
                Integer[] integers=CommonUtil.StringToInt(ingredientIds);
                for(int x:integers){
                    Ingredients ingredients=ingredientsMapper.findByIngredientsId(x);
                    if(ingredients!=null){
                        ingredientsList.add(ingredients);
                    }
                }
            }
        }
        ArrayList<Step> stepList=new ArrayList<>();
        if(!(menu.getStepIds()==null)){
            String[]stepIds= CommonUtil.split(menu.getStepIds());
            if(!stepIds[0].equals("")){
                Integer[] integerss=CommonUtil.StringToInt(stepIds);
                for(String s:stepIds){
                    System.out.println(s);
                }
                System.out.println(stepIds.length);
                log.info(integerss.toString());
                for(int x:integerss){
                    Step step= stepMapper.findByStepId(x);
                    if(step!=null){
                        stepList.add(step);
                    }
                }
            }
        }
        return ResponseResult.success("根据id查找食谱具体内容成功",menu,ingredientsList,stepList);
    }

    @Override
    public ResponseResult findMenuByNameLike(String key,Integer pageNow,Integer pageSize) {
        PageHelper.startPage(pageNow,pageSize);
        List<Menu> menuList=menuMapper.findByMenuNameLike(key);
        boolean result = redisUtil.hasKey(RedisKeyUtils.ALL_IN_SEARCH);
        if (!result){
            redisUtil.addZset(RedisKeyUtils.ALL_IN_SEARCH,key,1);
        }else{
            redisUtil.addScore(RedisKeyUtils.ALL_IN_SEARCH,key,1);
        }
        if(menuList.isEmpty()){
            PageHelper.startPage(pageNow,pageSize);
            List<Menu> menuList1=menuMapper.findAllMenuByStateOne();
            PageInfo<Menu> pageInfo=new PageInfo<>(menuList1);
            return ResponseResult.success("查询成功",pageInfo);
        }
        PageInfo<Menu> pageInfo=new PageInfo<>(menuList);
        return ResponseResult.success("查询成功",pageInfo);
    }

    @Override
    public ResponseResult findAllMenuByCollection(Integer pageNow, Integer pageSize) {
        PageHelper.startPage(pageNow,pageSize);
        List<Menu> menuList=menuMapper.findAllMenuByCollection();
        PageInfo<Menu> pageInfo=new PageInfo<>(menuList);
        return ResponseResult.success("查询成功",pageInfo);
    }

    @Override
    public ResponseResult findAllMenuByCollectionNameLike(String menuName, Integer pageNow, Integer pageSize) {
        PageHelper.startPage(pageNow,pageSize);
        List<Menu> menuList=menuMapper.findAllMenuByCollectionNameLike(menuName);
        if(menuList.isEmpty()){
            PageHelper.startPage(pageNow,pageSize);
            List<Menu> menuList1=menuMapper.findAllMenuByStateOne();
            PageInfo<Menu> pageInfo=new PageInfo<>(menuList1);
            return ResponseResult.success("查询成功",pageInfo);
        }
        PageInfo<Menu> pageInfo=new PageInfo<>(menuList);
        return ResponseResult.success("查询成功",pageInfo);
    }

    @Override
    public ResponseResult findAllMenuByDohNameLike(String menuName, Integer pageNow, Integer pageSize) {
        PageHelper.startPage(pageNow,pageSize);
        List<Menu> menuList=menuMapper.findAllMenuByDohNameLike(menuName);
        if(menuList.isEmpty()){
            PageHelper.startPage(pageNow,pageSize);
            List<Menu> menuList1=menuMapper.findAllMenuByStateOne();
            PageInfo<Menu> pageInfo=new PageInfo<>(menuList1);
            return ResponseResult.success("查询成功",pageInfo);
        }
        PageInfo<Menu> pageInfo=new PageInfo<>(menuList);
        return ResponseResult.success("查询成功",pageInfo);
    }

    @Override
    public ResponseResult addSteps(Integer userId, Integer menuId, List<Step> stepList) {
        User user= userMapper.findByUserId(userId);
        if(user==null){
            return ResponseResult.error("用户不存在");
        }
        Menu menu=menuMapper.findByMenuId(menuId);
        if (menu == null) {
            return ResponseResult.error("该菜单不存在");
        }
        ArrayList<Integer> arrayList=new ArrayList();
        ResponseResult responseResult=new ResponseResult();
        //填写步骤
        for (Step step:stepList){
            if(step!=null){
                stepMapper.addStep(step);
                arrayList.add(step.getStepId());
            }else{
                responseResult.setMessage("请填写完整的步骤信息");
                return responseResult;
            }
        }
        menuMapper.updateStepIds(arrayList.toString(),menuId);
        return ResponseResult.success("添加成功");
    }

    @Override
    public ResponseResult addIngredients(Integer menuId, List<Ingredients> ingredientsList) {
        Menu menu=menuMapper.findByMenuId(menuId);
        if (menu == null) {
            return ResponseResult.error("该菜单不存在");
        }
        ArrayList<Integer> arrayList=new ArrayList();
        ResponseResult responseResult=new ResponseResult();
        //填写步骤
        for (Ingredients ingredients:ingredientsList){
            if(ingredients!=null){
                ingredientsMapper.addIngredients(ingredients);
                arrayList.add(ingredients.getIngredientsId());
            }else{
                responseResult.setMessage("请填写完整的食材信息");
                return responseResult;
            }
        }
        menuMapper.updateIngredientsIds(arrayList.toString(),menuId);
        return ResponseResult.success("添加成功");
    }

    @Override
    public ResponseResult findMenuByUserId(Integer userId,Integer pageNow,Integer pageSize) {
        User user= userMapper.findByUserId(userId);
        if(user==null){
            return ResponseResult.error("用户不存在");
        }
        PageHelper.startPage(pageNow,pageSize);
        List<Menu> menuList=menuMapper.findMenuByUserId(userId);
        PageInfo<Menu> pageInfo=new PageInfo<>(menuList);
        return ResponseResult.success("查询成功",pageInfo);
    }

    @Override
    public ResponseResult verifyMenu(Integer menuId,Integer state) {
        Menu menu= menuMapper.findByMenuId(menuId);
        if(menu==null){
            return ResponseResult.error("菜谱不存在");
        }
        if(state==1){
            menuMapper.updateStateToOne(menuId);
            noticeService.addNotice("您的食谱"+menu.getMenuName()+"审核已经通过",menu.getUserId());
            return ResponseResult.success("该食谱审核已通过");
        }
        if(state==-1){
            if(menu.getState()==0){
                menuMapper.updateStateToZero(menuId);
                noticeService.addNotice("您的食谱"+menu.getMenuName()+"审核未通过,如果有什么疑问可以反馈哦~",menu.getUserId());
            }
            if(menu.getState()!=0){
                menuMapper.updateStateToZero(menuId);
                noticeService.addNotice("您的食谱"+menu.getMenuName()+"经过再次审核发现违规,审核未通过,如果有什么疑问可以反馈哦~",menu.getUserId());
            }
            return ResponseResult.success("该食谱审核未通过");
        }
        return ResponseResult.error("state只能是-1或者1");
    }

    @Override
    public ResponseResult findAllMenuSrc(Integer pageNow,Integer pageSize) {
        PageHelper.startPage(pageNow,pageSize);
        List<Menu> menuList=menuMapper.findAllMenuSrc();
        PageInfo<Menu> pageInfo=new PageInfo<>(menuList);
        return ResponseResult.success("查询成功",pageInfo);
    }

    @Override
    public ResponseResult addStep(Integer userId, Integer menuId, MultipartFile stepSrc,String content) {
        User user= userMapper.findByUserId(userId);
        if(user==null){
            return ResponseResult.error("用户不存在");
        }
        Menu menu= menuMapper.findByMenuId(menuId);
        if(menu==null){
            return ResponseResult.error("菜单不存在");
        }
        if(!userId.equals(menu.getUserId())){
            return ResponseResult.error("用户不是当前发布该食谱的用户");
        }
        ArrayList<String> arrayList=new ArrayList<>();
        Step step=new Step();
        step.setMenuId(menuId);
        step.setStepContent(content);
        stepMapper.addStep(step);
        ResponseResult responseResult=fileUtils.uploadStep(stepSrc,step.getStepId());
        if(responseResult.getCode()==200){
            Object object=responseResult.getObject();
            String fileName=(String)object;
            stepMapper.updateStepSrc(step.getStepId(),fileName);
        } else{
            return responseResult;
        }
        if(menu.getStepIds()!=null){
            arrayList=CommonUtil.splitAdd(menu.getStepIds());
        }
        String i= String.valueOf(step.getStepId());
        arrayList.add(i);
        menuMapper.updateStepIds(arrayList.toString(),menuId);
        return ResponseResult.success("添加步骤成功");
    }

    @Override
    public ResponseResult addIngredient(Integer userId, Integer menuId, String dosage, String ingredientsName) {
        User user= userMapper.findByUserId(userId);
        if(user==null){
            return ResponseResult.error("用户不存在");
        }
        Menu menu= menuMapper.findByMenuId(menuId);
        if(menu==null){
            return ResponseResult.error("菜单不存在");
        }
        if(!userId.equals(menu.getUserId())){
            return ResponseResult.error("用户不是当前发布该食谱的用户");
        }
        ArrayList<String> arrayList=new ArrayList<>();
        Ingredients ingredients=new Ingredients();
        ingredients.setIngredientsName(ingredientsName);
        ingredients.setDosage(dosage);
        ingredients.setMenuId(menuId);
        ingredientsMapper.addIngredients(ingredients);
        if(menu.getIngredientIds()!=null){
            arrayList=CommonUtil.splitAdd(menu.getIngredientIds());
        }
        String i= String.valueOf(ingredients.getIngredientsId());
        arrayList.add(i);
        menuMapper.updateIngredientsIds(arrayList.toString(),menuId);
        return ResponseResult.success("添加食材成功");
    }

    @Override
    public ResponseResult deleteMenu(Integer menuId,Integer userId) {
        Menu menu= menuMapper.findByMenuId(menuId);
        if(menu==null){
            return ResponseResult.error("菜单不存在");
        }
        User user= userMapper.findByUserId(userId);
        if(user==null){
            return ResponseResult.error("用户不存在");
        }
        if(!userId.equals(menu.getUserId())
                || user.getGrade()!=1){
            return ResponseResult.error("你没有权限删除");
        }
        ResponseResult responseResult=null;
        try{
            if(menu.getStepIds()!=null){
                String[] stepId=CommonUtil.split(menu.getStepIds());
                Integer[]stepIds= CommonUtil.StringToInt(stepId);
                for(int x:stepIds){
                    responseResult= stepService.deleteFile(userId,x);
                }
                stepMapper.batchDeleteStep(stepIds);
            }
            if(menu.getIngredientIds()!=null){
                String[] ingredientId=CommonUtil.split(menu.getIngredientIds());
                Integer[]ingredientIds= CommonUtil.StringToInt(ingredientId);
                ingredientsMapper.batchDeleteIngredients(ingredientIds);
            }
            menuMapper.deleteMenu(menuId);
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResponseResult.success("删除成功",responseResult.getMessage());
    }
    @Override
    public ResponseResult batchDeleteMenu(Integer[] menuId,Integer userId) {
        try{
            for(int i:menuId){
              ResponseResult responseResult=deleteMenu(i,userId);
                log.info(responseResult.getMessage());
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return ResponseResult.success("批量删除成功");
    }

    @Override
    public ResponseResult adminFindMenuByNameLike(String key, Integer pageNow, Integer pageSize) {
        PageHelper.startPage(pageNow,pageSize);
        List<Menu> menuList=menuMapper.adminFindByMenuNameLike(key);
        PageInfo<Menu> pageInfo=new PageInfo<>(menuList);
        return ResponseResult.success("查询成功",pageInfo);
    }

    @Override
    public ResponseResult deleteMenuSrc(Integer menuId, Integer userId) {
        User user= userMapper.findByUserId(userId);
        if(user==null){
            return ResponseResult.error("用户不存在");
        }
        if(user.getGrade()!=1){
            return ResponseResult.error("不是管理员没有权限删除照片");
        }
        Menu menu= menuMapper.findByMenuId(menuId);
        if(menu==null){
            return ResponseResult.error("该菜谱不存在");
        }
        menuMapper.updateMenuSrc("",menuId);
        return ResponseResult.error("删除成功");
    }
}
